//
//  FileManage.m
//  CheckIn
//
//  Created by bryan.ren on 17/01/2018.
//  Copyright © 2018 bryan. All rights reserved.
//

#import "FileManage.h"
#import "CommonDefine.h"
#import "StringAndDateHandle.h"

@implementation FileManage

+ (NSString *)document {
    NSArray *directoryArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = directoryArr.firstObject;
    return documentDirectory;
}

+ (NSString *)overtimeDirectory {
    NSString *dir = [[self document] stringByAppendingPathComponent:kOverTimeDir];
    return dir;
}

+ (NSString *)currentMonthFile
{
    NSDate *now = [NSDate date];
    NSString *currentMonth = [[StringAndDateHandle sharedInstance] dateToString:now formatter:kDateYM];
    currentMonth = [currentMonth stringByAppendingPathExtension:@"json"];
    NSString *currentMonthPath = [[self overtimeDirectory] stringByAppendingPathComponent:currentMonth];
    return currentMonthPath;
}

+ (BOOL)createFileDirectory
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *overtimePath = [FileManage overtimeDirectory];
    BOOL isDic;
    BOOL isCreate = NO;
    if (![fileManager fileExistsAtPath:overtimePath isDirectory:&isDic]) {
        isCreate = [fileManager createDirectoryAtPath:overtimePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    else {
        isCreate = YES;
    }
    return isCreate;
}

+ (BOOL)directoryIsExists
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *overtimePath = [FileManage overtimeDirectory];
    BOOL isDic;
    BOOL exists = [fileManager fileExistsAtPath:overtimePath isDirectory:&isDic];
    if (isDic && exists) {
        return YES;
    }
    return NO;
}

+ (NSArray<NSURL *> *)fileArray
{
    if ([FileManage directoryIsExists]) {
        NSArray<NSURL *> *files = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:[NSURL URLWithString:[FileManage overtimeDirectory]] includingPropertiesForKeys:@[] options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"pathExtension == 'json'"];
        for (NSURL *fileURL in [files filteredArrayUsingPredicate:predicate]) {
            NSLog(@"%@", fileURL);
        }
        return files;
    }
    return nil;
}

+ (NSArray *)fileContent:(NSURL *)url
{
    NSString *contents = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
    if (contents && ![contents isEqualToString:@""]) {
        NSArray *contentList = [contents componentsSeparatedByString:@"\r\n"];
        return contentList;
    }
    return nil;
}

@end
